package edu.cuit.zhuyimeng.framework.security.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.same.SaSameUtil;
import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.json.JSONUtil;
import edu.cuit.zhuyimeng.framework.common.result.CommonResult;
import edu.cuit.zhuyimeng.framework.security.security.StpInterfaceImpl;
import edu.cuit.zhuyimeng.uaa.api.controller.AuthenticationApiController;
import edu.cuit.zhuyimeng.uaa.api.controller.VerificationApiController;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@AutoConfiguration
@ConditionalOnClass({DispatcherServlet.class,SaServletFilter.class})
@RequiredArgsConstructor
@EnableFeignClients(basePackages = "edu.cuit.zhuyimeng.uaa.api.controller")
public class SecurityAutoConfiguration implements WebMvcConfigurer {

    @Bean
    public SaServletFilter getSaServletFilter() {

        return new SaServletFilter()
                .addInclude("/**")
                .addExclude("/favicon.ico")
                .setAuth(obj -> {

                    if (!SaHolder.getRequest().getUrl().contains("v3/api-docs")) {
                        String token = SaHolder.getRequest().getHeader(SaSameUtil.SAME_TOKEN);
                        SaSameUtil.checkToken(token);
                    }
                })
                .setError(e -> JSONUtil.toJsonStr( CommonResult.error(e.getMessage())));
    }

    @Bean
    @ConditionalOnMissingClass("edu.cuit.zhuyimeng.uaa.AuthorizationServerApplication")
    public StpInterface stpInterface(AuthenticationApiController authenticationApiController, VerificationApiController verificationApiController) {
        return new StpInterfaceImpl(authenticationApiController, verificationApiController);
    }

}
